package com.demo.es;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;

/**
 * 描述: search文档检索
 *
 * @author : lhb
 * @date : 2019-11-05 14:34
 */
public class SearchApi {

    /**
     * 搜索数据 高亮
     */
    public void highLightSearch(RestHighLevelClient client) {
        SearchRequest searchRequest = new SearchRequest(
                "posts");

        //查询高亮
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        HighlightBuilder highlightBuilder = new HighlightBuilder();

        //对name字段进行高亮显示
        HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("name");
        highlightTitle.highlighterType("unified");
        highlightBuilder.field(highlightTitle);

        searchSourceBuilder.highlighter(highlightBuilder);

        //查询出来所有包含name字段且name字段包含 生命的诞生值 的文档 模糊查询
        searchSourceBuilder.query(QueryBuilders.matchQuery("name", "命"));

        //将请求体加入到请求中
        searchRequest.source(searchSourceBuilder);
        try {
            //3、发送请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println("--------------------搜索高亮文档---------------------");
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits.getHits()) {
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField highlight = highlightFields.get("name");
                if (highlight != null) {
                    Text[] fragments = highlight.fragments();
                    String fragmentString = fragments[0].string();
                    System.out.println(fragmentString);
                }
            }

            System.out.println(Arrays.toString(searchResponse.getHits().getHits()));
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
